package com.jmb.waimao.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Client for the Mail Control Protocol (MCP) Email Service
 */
@Slf4j
public class MCPEmailClient {
    
    private final String baseUrl;
    private final RestTemplate restTemplate;
    
    /**
     * Create a new MCP Email Client
     * 
     * @param baseUrl Base URL of the MCP Email Service
     */
    public MCPEmailClient(String baseUrl) {
        this.baseUrl = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
        this.restTemplate = new RestTemplate();
    }
    
    /**
     * Send a simple email
     * 
     * @param to Recipient email address
     * @param subject Email subject
     * @param content Email content (can be HTML)
     * @return Response from the server
     */
    public Map<String, Object> sendEmail(String to, String subject, String content) {
        try {
            String url = baseUrl + "api/mcp/send";
            
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("to", to);
            map.add("subject", subject);
            map.add("content", content);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
            
            ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
            return response.getBody();
        } catch (Exception e) {
            log.error("Failed to send email: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "Failed to send email: " + e.getMessage());
            return errorResponse;
        }
    }
    
    /**
     * Send a templated email
     * 
     * @param to Recipient email address
     * @param subject Email subject (optional)
     * @param templateId ID of the template to use
     * @param variables Variables to replace in the template
     * @return Response from the server
     */
    public Map<String, Object> sendTemplatedEmail(String to, String subject, Long templateId, Map<String, Object> variables) {
        try {
            String url = baseUrl + "api/mcp/send-templated?to=" + to;
            
            if (subject != null && !subject.isEmpty()) {
                url += "&subject=" + subject;
            }
            
            url += "&templateId=" + templateId;
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(variables, headers);
            
            ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
            return response.getBody();
        } catch (Exception e) {
            log.error("Failed to send templated email: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "Failed to send templated email: " + e.getMessage());
            return errorResponse;
        }
    }
    
    /**
     * Get the status of the email service
     * 
     * @return Status information
     */
    public Map<String, Object> getStatus() {
        try {
            String url = baseUrl + "api/mcp/status";
            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            return response.getBody();
        } catch (Exception e) {
            log.error("Failed to get email service status: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "Failed to get email service status: " + e.getMessage());
            return errorResponse;
        }
    }
    
    /**
     * Configure the email service
     * 
     * @param config Configuration parameters
     * @return Response from the server
     */
    public Map<String, Object> configure(Map<String, Object> config) {
        try {
            String url = baseUrl + "api/mcp/configure";
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(config, headers);
            
            ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
            return response.getBody();
        } catch (Exception e) {
            log.error("Failed to configure email service: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "Failed to configure email service: " + e.getMessage());
            return errorResponse;
        }
    }
}
